<template>
    <div class="container">
        <el-card class="box-card">
            <el-form ref="form" :model="form" :rules="rules" label-position="top">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="APP名称" prop="package_name">
                            <el-select v-model="form.package_name" placeholder="请选择APP" filterable clearable
                                style="width: 100%">
                                <el-option v-for="item in appList" :key="item.id" :label="item.shortName"
                                    :value="item.package_name" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="当前版本" prop="c_version">
                            <el-input v-model="form.c_version" placeholder="请输入当前版本号" clearable />
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="更新简述" prop="update_summary">
                            <el-input v-model="form.update_summary" type="textarea" :rows="3" placeholder="请输入更新简介" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="商店地址" prop="update_url">
                            <el-input v-model="form.update_url" placeholder="请输入更新地址" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <!-- 在需要放置的位置添加这个按钮 -->
                    <el-form-item label="更新文案">
                        <el-button type="primary" @click="dialogVisible = true"
                            icon="el-icon-circle-plus">添加多语言文案</el-button>
                    </el-form-item>

                    <!-- 动态生成的文案输入区域 -->
                    <template v-for="(lang, index) in selectedLanguages">
                        <el-col :span="12">
                            <el-form-item :key="index" :label="`${lang.zh}-${lang.code}`" :prop="'content.' + lang.code"
                                :rules="contentRules">

                                <vue-editor v-model="form.content[lang.code]"></vue-editor>
                            </el-form-item>
                        </el-col>
                    </template>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="更新版本范围" required>
                            <div class="version-range">
                                <el-form-item prop="min_version" class="range-item">
                                    <el-input v-model="form.min_version" placeholder="最小版本 ≥" clearable />
                                </el-form-item>
                                <span class="range-separator">至</span>
                                <el-form-item prop="max_version" class="range-item">
                                    <el-input v-model="form.max_version" placeholder="最大版本 ≤" clearable />
                                </el-form-item>
                            </div>
                        </el-form-item>
                    </el-col>

                </el-row>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="更新类型" prop="update_type">
                            <el-select v-model="form.update_type" placeholder="请选择更新类型" style="width: 100%">
                                <el-option label="选择更新" :value="0" />
                                <el-option label="强制更新" :value="1" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                </el-row>

                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="生效时间" prop="effective_datetime">
                            <el-date-picker v-model="form.effective_datetime" type="datetime" placeholder="选择生效时间"
                                value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH"
                                :picker-options="pickerOptions" style="width: 100%"
                                @change="onChangeEffectiveDatetime" />
                        </el-form-item>
                    </el-col>

                </el-row>
                <div class="form-footer">
                    <el-button @click="handleCancel">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">提交</el-button>
                </div>
            </el-form>
            <!-- 语言选择弹窗 -->
            <el-dialog title="选择语言" :visible.sync="dialogVisible" width="60%">
                <div class="language-select">
                    <el-checkbox-group v-model="selectedLangIndexes">
                        <el-row :gutter="20">
                            <el-col v-for="(lang, index) in zhCN" :key="index" :span="6" style="margin-bottom: 15px">
                                <el-checkbox :label="index">{{ lang }}</el-checkbox>
                            </el-col>
                        </el-row>
                    </el-checkbox-group>
                </div>
                <span slot="footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmLanguages">确定</el-button>
                </span>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
import { getAppList, save } from "@/api/appVersion";
import moment from 'moment'
// Basic Use - Covers most scenarios
import { VueEditor } from "vue2-editor";


export default {
    name: 'VersionForm',
    components: {
        VueEditor
    },
    data() {
        return {
             
            // BCP47: [
            //     'et_EE', 'bg_BG', 'pl_PL', 'da_DK', 'de_DE', 'ru_RU', 'fr_FR', 'fi_FI', 'nl_NL', 'cs_CZ',
            //     'lv_LV', 'lt_LT', 'ro_RO', 'pt_PT', 'sv_SE', 'nb_NO', 'sk_SK', 'sl_SI', 'tr_TR', 'uk_UA',
            //     'es_ES', 'el_GR', 'hu_HU', 'it_IT', 'ca_ES', 'eu_ES', 'ga_IE', 'is_IS', 'mt_MT', 'sr_RS',
            //     'ko_KR', 'ja_JP', 'zh_CN', 'zh_TW', 'zh_HK', 'th_TH', 'vi_VN', 'ms_MY', 'fil_PH', 'km_KH',
            //     'lo_LA', 'my_MM', 'ta_IN', 'te_IN', 'kn_IN', 'ml_IN', 'bn_BD', 'si_LK', 'ur_PK', 'ps_AF',
            //     'sw_KE', 'yo_NG', 'ha_NE', 'zu_ZA', 'xh_ZA', 'st_ZA', 'rw_RW', 'so_SO', 'am_ET', 'ig_NG',
            //     'ar_SA', 'he_IL', 'fa_IR', 'ku_TR', 'arc_IQ', 'syr_SY', 'ckb_IQ',
            //     'en_US', 'es_MX', 'pt_BR', 'quz_PE', 'gn_PY', 'ay_BO', 'nah_MX', 'iu_CA',
            //     'mi_NZ', 'haw_US', 'ty_PF',
            //     'hi_IN', 'mr_IN', 'gu_IN', 'pa_IN', 'or_IN', 'as_IN', 'ne_NP', 'dv_MV',
            //     'en_GB', 'eo', 'ia', 'jbo', 'tok'
            // ],
            // zhCN: [
            //     '爱沙尼亚语', '保加利亚语', '波兰语', '丹麦语', '德语', '俄语', '法语', '芬兰语', '荷兰语', '捷克语',
            //     '拉脱维亚语', '立陶宛语', '罗马尼亚语', '葡萄牙语(葡萄牙)', '瑞典语', '书面挪威语', '斯洛伐克语', '斯洛文尼亚语', '土耳其语', '乌克兰语',
            //     '西班牙语(西班牙)', '希腊语', '匈牙利语', '意大利语', '加泰罗尼亚语', '巴斯克语', '爱尔兰语', '冰岛语', '马耳他语', '塞尔维亚语',
            //     '韩语', '日语', '中文(简体)', '中文(繁体)', '中文(香港)', '泰语', '越南语', '马来语', '菲律宾语', '高棉语',
            //     '老挝语', '缅甸语', '泰米尔语', '泰卢固语', '卡纳达语', '马拉雅拉姆语', '孟加拉语', '僧伽罗语', '乌尔都语', '普什图语',
            //     '斯瓦希里语', '约鲁巴语', '豪萨语', '祖鲁语', '科萨语', '南索托语', '卢旺达语', '索马里语', '阿姆哈拉语', '伊博语',
            //     '阿拉伯语(沙特)', '希伯来语', '波斯语', '库尔德语', '阿拉米语', '叙利亚语', '中库尔德语',
            //     '英语(美式)', '西班牙语(墨西哥)', '葡萄牙语(巴西)', '克丘亚语', '瓜拉尼语', '艾马拉语', '纳瓦特尔语', '因纽特语',
            //     '毛利语', '夏威夷语', '塔希提语',
            //     '印地语', '马拉地语', '古吉拉特语', '旁遮普语', '奥里亚语', '阿萨姆语', '尼泊尔语', '迪维希语',
            //     '英语(英式)', '世界语', '国际语', '逻辑语', '道本语'
            // ],
            zhCN: [
                '英语', '葡萄牙语', '西班牙语', '德语', '法语', '意大利语', '俄罗斯语','印度尼西亚语','日语','韩语','土耳其语','印地语','中文(繁体)','中文(简体)','荷兰语','阿拉伯语'
            ],
            BCP47: ['en_US', 'pt_PT', 'es_ES', 'de_DE', 'fr_FR', 'it_IT', 'ru_RU', 'id_ID', 'ja_JP', 'ko_KR', 'tr_TR', 'hi_IN', 'zh_TW', 'zh_CN', 'nl_NL','ar_SA'],
            dialogVisible: false,
            selectedLangIndexes: [], // 存储选中的语言索引
            selectedLanguages: [], // 存储选中的语言对象
            contentRules: { required: true, message: '文案不能为空', trigger: 'blur' },
            form: {
                package_name: '',
                c_version: '',
                update_summary: '',
                update_type: 0,
                update_url: '',
                min_version: '',
                max_version: '',
                effective_datetime: '',
                effective_timestamp: 0,
                content: {}
            },
            appList: [],
            submitLoading: false,
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7
                }
            },
            rules: {
                package_name: [
                    { required: true, message: '请选择APP', trigger: 'blur' }
                ],
                c_version: [
                    { required: true, message: '请输入当前版本号', trigger: 'blur' },
                    { validator: this.validateVersionFormat, trigger: 'blur' }
                ],
                update_summary: [
                    { required: true, message: '请输入更新简介', trigger: 'blur' }
                ],
                update_type: [
                    { required: true, message: '请选择更新类型', trigger: 'change' }
                ],
                update_url: [
                    { required: true, message: '请输入更新地址', trigger: 'blur' }
                ],
                min_version: [
                    { required: true, message: '请输入最小版本', trigger: 'blur' },
                    { validator: this.validateVersionFormat, trigger: 'blur' }
                ],
                max_version: [
                    { required: true, message: '请输入最大版本', trigger: 'blur' },
                    { validator: this.validateVersionFormat, trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            // 如果当前版本或最大版本都存在，则比较
                            if (value && this.form.c_version) {
                                if (this.compareVersion(value, this.form.c_version) === 1) {
                                    return callback(new Error('最大版本必须小于等于当前版本'));
                                }
                            }
                            callback();
                        },
                        trigger: 'blur'
                    }
                ],
                effective_datetime: [
                    { required: true, message: '请选择生效时间', trigger: 'change' }
                ]
            }
        }
    },
    created() {
        this.getAppList()
        // 如果携带了编辑数据
        if (this.$route.query.formData) {
            const formData = JSON.parse(this.$route.query.formData)
            // 假设后端返回的 update_details 是类似于 [{"et_EE":"312"},{"de_DE":"123"}] 的格式
            const detailArray = JSON.parse(formData.update_details || '[]');
            // 把数组转成形如 { et_EE: '312', de_DE: '123' } 的对象
            const contentObj = {};
            detailArray.forEach((item) => {
                const key = Object.keys(item)[0];
                contentObj[key] = item[key];
            });

            // 把转换好的对象放进 form.content
            this.form = {
                ...formData,
                content: contentObj,
            };

            // 使用内置的多语言初始化方法来恢复勾选状态、selectedLangIndexes 等
            this.initEditData({ content: JSON.stringify(contentObj) });
            
        }
    },
    methods: {
        compareVersion(v1, v2) {
            const segments1 = v1.split('.').map(Number);
            const segments2 = v2.split('.').map(Number);
            const len = Math.max(segments1.length, segments2.length);
            for (let i = 0; i < len; i++) {
                const num1 = segments1[i] || 0;
                const num2 = segments2[i] || 0;
                if (num1 > num2) return 1;
                if (num1 < num2) return -1;
            }
            return 0;
        },
        validateVersionFormat(rule, value, callback) {
            // 只允许匹配格式：数字.数字.数字
            const versionPattern = /^\d+\.\d+\.\d+$/;
            if (!value) {
                return callback(new Error('请输入版本号'));
            } else if (!versionPattern.test(value)) {
                return callback(new Error('版本号格式不正确，应为 x.x.x 格式'));
            } else {
                return callback();
            }
        },
        onChangeEffectiveDatetime(value) {
            if (value) {
                // 使用 JavaScript 新 Date() 处理也可以，以下为示例：
                const date = new Date(value)
                // 将分钟、秒和毫秒设置为 0
                date.setMinutes(0)
                date.setSeconds(0)
                date.setMilliseconds(0)
                // 重新格式化为字符串
                const year = date.getFullYear()
                const month = ("0" + (date.getMonth() + 1)).slice(-2)
                const day = ("0" + date.getDate()).slice(-2)
                const hour = ("0" + date.getHours()).slice(-2)
                this.form.effective_datetime = `${year}-${month}-${day} ${hour}:00:00`
            }
        },
        htmlToText(html) {
            const div = document.createElement('div');
            div.innerHTML = html;
            return div.textContent || div.innerText || "";
        },
        // 构造格式为 [{ et_EE: '爱沙尼亚语' }, ...] 的数组
        transformContent() {
            const result = [];
            for (const key in this.form.content) {
                if (this.form.content.hasOwnProperty(key)) {
                    const text = this.form.content[key];
                    const obj = {};
                    obj[key] = text;
                    result.push(obj);
                }
            }
            return result;
        },
        // 修复后的确认选择方法
        confirmLanguages() {
            // 过滤无效索引
            const validIndexes = this.selectedLangIndexes.filter(index =>
                index >= 0 &&
                index < this.BCP47.length &&
                index < this.zhCN.length
            )

            // 生成新的选中语言列表
            const newSelected = validIndexes.map(index => ({
                code: this.BCP47[index],
                zh: this.zhCN[index]
            }))
            // 保留已存在的输入内容
            newSelected.forEach(lang => {
                if (!this.form.content[lang.code]) {
                    this.$set(this.form.content, lang.code, '')
                }
            })
            // 移除取消选择的语言
            const removedLanguages = this.selectedLanguages.filter(
                lang => !newSelected.some(n => n.code === lang.code)
            )
            removedLanguages.forEach(lang => {
                this.$delete(this.form.content, lang.code)
            })

            this.selectedLanguages = newSelected
            this.dialogVisible = false
        },

        // 删除语言
        removeLanguage(index) {
            const removedLang = this.selectedLanguages[index]
            this.$delete(this.form.content, removedLang.code)
            this.selectedLanguages.splice(index, 1)

            // 同步更新选中的索引
            const codeIndex = this.BCP47.indexOf(removedLang.code)
            this.selectedLangIndexes = this.selectedLangIndexes.filter(
                i => i !== codeIndex
            )
        },

        // 检查是否已选（用于禁用已选中的复选框）
        isLanguageSelected(index) {
            return this.selectedLanguages.some(
                lang => this.BCP47[index] === lang.code
            )
        },

        // 初始化编辑数据
        initEditData(formData) {
            if (formData.content) {
                try {
                    const content = JSON.parse(formData.content)
                    this.form.content = content
                    // 获取有效索引
                    this.selectedLangIndexes = Object.keys(content)
                        .map((code) => this.BCP47.indexOf(code))
                        .filter((index) => index !== -1);

                    this.selectedLanguages = this.selectedLangIndexes
                        .filter((index) => index < this.BCP47.length && index < this.zhCN.length)
                        .map((index) => ({
                            code: this.BCP47[index],
                            zh: this.zhCN[index],
                        }));
                } catch (error) {
                    console.error("解析多语言内容失败:", error);
                }
            }
        },
        async getAppList() {
            try {
                const { data } = await getAppList()
                this.appList = data
            } catch (error) {
                console.error('获取APP列表失败:', error)
            }
        },

        handleCancel() {
            this.$router.go(-1)
        },

        async handleSubmit() {
            
            this.$refs.form.validate(async valid => {
                if (valid) {
                    try {
                        this.submitLoading = true;
                        // 转换生效时间为 timestamp
                        this.form.effective_timestamp = moment(this.form.effective_datetime)
                            .utc()
                            .valueOf();

                        // 如果需要提交的 content 以数组形式传递，
                        // 可先转换 form.content
                        const transformedContent = this.transformContent();
                    
                        // 如果接口期望的 content 为字符串，可将数组再 stringify 掉
                        // const contentStr = JSON.stringify(transformedContent);
                        // 或者直接将数组提交，取决于后端需求
                        const formCopy = JSON.parse(JSON.stringify(this.form));
                        formCopy.content = JSON.stringify(transformedContent)
                        const submitData = {
                            ...formCopy
                             
                        }
                        console.log('提交数据：', submitData);
                        await save(submitData);  // 假设的更新接口
                        this.$message.success('success');
                        this.$router.replace({
                            path: '/appVersion',
                            query: { refresh: true }  // 通过 query 传递参数
                        });
                    } catch (error) {
                        console.error('提交失败:', error);
                    } finally {
                        this.submitLoading = false;
                    }
                }
            });
        }
    }
}
</script>

<style lang="scss" scoped>
::v-deep .ql-snow .ql-picker-label::before {
    transform: translateY(-7px);
}

.selected-tags {
    margin-top: 10px;
}



.el-form-item__content {
    display: flex;
    align-items: center;
}

.container {
    padding: 20px;

    .box-card {
        margin: 0 auto;
    }

    .version-range {
        display: flex;
        align-items: center;

        .range-item {
            flex: 1;
            margin-bottom: 0;
        }

        .range-separator {
            margin: 0 10px;
            color: #606266;
        }
    }

    .form-footer {
        margin-top: 30px;
        text-align: center;
    }
}

.el-select,
.el-date-editor {
    width: 100%;
}
</style>